package com.lbloca.locate.ui.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.lbloca.locate.R;
import com.lbloca.locate.application.LoApplication;
import com.lbloca.locate.biz.AppBiz;
import com.lbloca.locate.biz.Config;
import com.lbloca.locate.biz.UserBiz;
import com.lbloca.locate.ui.base.BaseActivity;
import com.lbloca.locate.ui.fragment.AttentionFragment;
import com.lbloca.locate.ui.fragment.LocationFragment;
import com.lbloca.locate.ui.fragment.MeFragment;
import com.lbloca.locate.utils.AppUtils;
import com.lbloca.locate.utils.FragmentManagerHelper;
import com.lbloca.locate.utils.LocationService;
import com.lbloca.locate.utils.LogUtils;
import com.lbloca.locate.utils.PermissionUtils;
import com.lbloca.locate.utils.SPUtils;
import com.lbloca.locate.weight.AgreeDialog;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;

public class MainActivity extends BaseActivity {
    private static final String TAG ="MainActivity";

    @BindView(R.id.id_ll)
    LinearLayout linearBottom;
    private FragmentManagerHelper mFragmentManagerHelper;
    private LocationService locationService;
    private LocationFragment locationFragment;
    private AttentionFragment mAttentionFragment;
    private List<Fragment> fragments = new ArrayList<>();
    private int[] mIconSelectIds = {
            R.drawable.aixingliangse, R.drawable.location, R.drawable.wodeliangse};
    private int[] mIconUnselectIds = {
            R.drawable.aixinghuise, R.drawable.locationhuise, R.drawable.wodehuise};

    @Override
    protected void initEvents() {

    }

    @Override
    protected void initData() {
        mFragmentManagerHelper = new FragmentManagerHelper(getSupportFragmentManager(), R.id.id_fl_content);
        mAttentionFragment = AttentionFragment.getInstance();
        fragments.add(mAttentionFragment);
        locationFragment = LocationFragment.getInstance();
        fragments.add(locationFragment);
        fragments.add(MeFragment.getInstance());
        mFragmentManagerHelper.addAll(fragments);
        mFragmentManagerHelper.switchFragment(0);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {
//        PermissionUtils.requestPermission(this, new String[]{Manifest.permission.READ_PHONE_STATE}, new PermissionUtils.Callback() {
//            @Override
//            public void onGranted(String permission) {
//                register(AppUtils.getPhoneNumber());
//            }
//
//            @Override
//            public void onDenied(String permission) {
//                register("");
//            }
//        });



        PermissionUtils.requestPermission(MainActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, new PermissionUtils.Callback() {
            @Override
            public void onGranted(String permission) {
                if (permission.equals(Manifest.permission.ACCESS_COARSE_LOCATION)) {
                    locationService = ((LoApplication) AppUtils.getContext()).locationService;
                    locationService.registerListener(mListener);
                    locationService.start();// 定位SDK
                }
            }

            @Override
            public void onDenied(String permission) {

            }
        });


        if (!SPUtils.getInstance().getBoolean(Config.SPF_PRIVACY))
            new AgreeDialog(this).show();
    }

    private void register(String phone) {
        AppBiz.getInstance().register(phone, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(String response, int id) {
                Log.e("response", response + "");
                if (!TextUtils.isEmpty(response) && response.contains("id")) {
                    UserBiz.getInstance().setUserInfo(response);
                    PermissionUtils.requestPermission(MainActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, new PermissionUtils.Callback() {
                        @Override
                        public void onGranted(String permission) {
                            if (permission.equals(Manifest.permission.ACCESS_COARSE_LOCATION)) {
                                locationService = ((LoApplication) AppUtils.getContext()).locationService;
                                locationService.registerListener(mListener);
                                locationService.start();// 定位SDK
                            }
                        }

                        @Override
                        public void onDenied(String permission) {

                        }
                    });
                }
            }
        });
    }

    @OnClick({R.id.id_ll_attention, R.id.id_iv_location, R.id.id_ll_me})
    void onClick(View v) {
        switch (v.getId()) {
            case R.id.id_ll_attention:
                mFragmentManagerHelper.switchFragment(0);
                updateBottomUI(0);
                break;
            case R.id.id_iv_location:
                mFragmentManagerHelper.switchFragment(1);
                updateBottomUI(1);
                break;
            case R.id.id_ll_me:
                mFragmentManagerHelper.switchFragment(2);
                updateBottomUI(2);
        }
    }

    private BDAbstractLocationListener mListener = new BDAbstractLocationListener() {
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (null != location && location.getLocType() != BDLocation.TypeServerError) {
//                if (location.getFloor() != null) {
//                    // 当前支持高精度室内定位
//                    locationService.getLocationClient().startIndoorMode();// 开启室内定位模式（重复调用也没问题），开启后，定位SDK会融合各种定位信息（GPS,WI-FI，蓝牙，传感器等）连续平滑的输出定位结果；
//                }
                locationFragment.mLocation = location;
                mAttentionFragment.mLocation = location;
                if (locationFragment != null){
                    locationFragment.changeMap();
                }
                if(mAttentionFragment!=null){
                    mAttentionFragment.changeMap();
                }

                AppBiz.getInstance().putAddress(location.getAddrStr(), location.getLatitude(), location.getLongitude(), null);


            }
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        OkHttpUtils.get().url(Config.VERSION_SWITCH).addParams("key", "gy_location").tag(this).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(String response, int id) {
                LogUtils.i(TAG,response);
                if (!TextUtils.isEmpty(response)) {
                    try {
                        JSONObject object = new JSONObject(response);
                        if (object != null) {
                            JSONObject versionObj = object.optJSONObject(AppUtils.getVersionName());
                            if (versionObj != null) {
                                SPUtils.getInstance().put(Config.BTN_ALIPAY, versionObj.optBoolean("alipay"));
                                SPUtils.getInstance().put(Config.BTN_WECHAT, versionObj.optBoolean("weixin"));
                                Config.SERVICES = object.optJSONObject("services");
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (locationService != null) {
            locationService.unregisterListener(mListener); //注销掉监听
            locationService.stop(); //停止定位服务
            locationService.getLocationClient().startIndoorMode();
            locationService = null;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionUtils.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    private void updateBottomUI(int position) {
        for (int i = 0, count = linearBottom.getChildCount(); i < count; i++) {
            ViewGroup viewGroup = (ViewGroup) linearBottom.getChildAt(i);
            ImageView img = (ImageView) viewGroup.getChildAt(0);
            TextView tv = (TextView) viewGroup.getChildAt(1);
            if (position == i) {
                img.setImageResource(mIconSelectIds[i]);
                if (tv != null)
                    tv.setTextColor(ContextCompat.getColor(this, R.color.tab_select_color));
            } else {
                img.setImageResource(mIconUnselectIds[i]);
                if (tv != null)
                    tv.setTextColor(ContextCompat.getColor(this, R.color.tab_unselect_color));
            }
        }
    }


    public  void goLocationPage(){
        mFragmentManagerHelper.switchFragment(1);
        updateBottomUI(1);
    }



    public static void start(Context context){
        Intent intent = new Intent(context,MainActivity.class);
        context.startActivity(intent);
    }

}
